package com.zmx.patientend.view.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.zmx.patientend.BaseActivity;
import com.zmx.patientend.R;
import com.zmx.patientend.adapter.city_picker.AreaAdapter;
import com.zmx.patientend.adapter.city_picker.CityAdapter;
import com.zmx.patientend.adapter.city_picker.ProvinceAdapter;
import com.zmx.patientend.okhttp.OkHttp3ClientManager;
import com.zmx.patientend.pojo.CityInfoBean;
import com.zmx.patientend.utils.AllUtil;
import com.zmx.patientend.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AddAddressActivity extends BaseActivity {


    @BindView(R.id.name)
    EditText name;
    @BindView(R.id.phone)
    EditText phone;
    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.save)
    Button save;
    @BindView(R.id.tool_bar)
    Toolbar toolBar;
    @BindView(R.id.e_address)
    EditText eAddress;

    private String s_province = "", s_city = "", s_county = "";
    private String s_province_name = "", s_city_name = "", s_county_name = "";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_address;
    }

    @Override
    protected void initViews() {

        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);

        beans = new ArrayList<>();
        c_beans = new ArrayList<>();
        a_beans = new ArrayList<>();
    }


    @OnClick({R.id.address, R.id.save})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.address:
                getArea();

                break;
            case R.id.save:
                addAddress();
                break;
        }
    }


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    try {

                        beans.clear();

                        JSONObject object = new JSONObject(msg.obj.toString());
                        JSONArray data = object.getJSONArray("data");
                        Gson gson = new Gson();
                        for (int i = 0; i < data.length(); i++) {

                            CityInfoBean bean1 = gson.fromJson(data.getJSONObject(i).toString(), CityInfoBean.class);//解析
                            beans.add(bean1);

                        }
                        showPhoto();

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 2:

                    try {

                        c_beans.clear();
                        cityList.clear();
                        JSONObject object = new JSONObject(msg.obj.toString());
                        JSONArray data = object.getJSONArray("data");
                        Gson gson = new Gson();
                        for (int i = 0; i < data.length(); i++) {

                            CityInfoBean bean1 = gson.fromJson(data.getJSONObject(i).toString(), CityInfoBean.class);//解析
                            c_beans.add(bean1);
                            cityList.add(bean1.getAreaName());
                        }

                        initCity();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case 3:

                    try {

                        a_beans.clear();
                        areaList.clear();
                        JSONObject object = new JSONObject(msg.obj.toString());
                        JSONArray data = object.getJSONArray("data");
                        Gson gson = new Gson();
                        for (int i = 0; i < data.length(); i++) {

                            CityInfoBean bean1 = gson.fromJson(data.getJSONObject(i).toString(), CityInfoBean.class);//解析
                            a_beans.add(bean1);
                            areaList.add(bean1.getAreaName());
                        }

                        initArea();

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 4:
                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Toast(object.getString("msg"));
                        if (object.getInt("code") == 1){
                            finish();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;


            }

        }
    };


    public void getArea(String areaId, int state) {


        List<String> ls = new ArrayList<>();
        ls.add(areaId);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getArea");
        params.put("data[areaId]", areaId);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/mall/", params, handler, state, 404);


    }

    public void getArea() {


        List<String> ls = new ArrayList<>();
        ls.add("-1");
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getArea");
        params.put("data[areaId]", "-1");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/mall/", params, handler, 1, 404);


    }

    private Dialog modify_dialogs;//弹出框
    RecyclerView mRvProvince;
    RecyclerView mRvCity;
    RecyclerView mRvArea;
    ArrayList<CityInfoBean> beans;
    ArrayList<CityInfoBean> c_beans;
    ArrayList<CityInfoBean> a_beans;
    List<String> provinceList = new ArrayList<>();
    List<String> cityList = new ArrayList<>();
    List<String> areaList = new ArrayList<>();
    CityAdapter mCityAdapter;
    AreaAdapter mAreaAdapter;
    ProvinceAdapter mProvinceAdapter;
    String province, city, area;
    CityInfoBean mCityInfoBean;
    TextView mTvProvince;
    TextView mTvCity;
    TextView mTvArea;
    ImageView mImgClose;
    LinearLayout mLlSelect;

    public void showPhoto() {

        View view;//选择性别的view

        modify_dialogs = new Dialog(mActivity, R.style.ActionSheetDialogStyle);
        //填充对话框的布局
        view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_city_picker, null);
        mRvProvince = view.findViewById(R.id.rv_province);
        mRvCity = view.findViewById(R.id.rv_city);
        mRvArea = view.findViewById(R.id.rv_area);
        mTvProvince = view.findViewById(R.id.tv_province);
        mTvCity = view.findViewById(R.id.tv_city);
        mTvArea = view.findViewById(R.id.tv_area);
        mLlSelect = view.findViewById(R.id.ll_select);
        mImgClose = view.findViewById(R.id.img_close);
        //将布局设置给Dialog
        modify_dialogs.setContentView(view);
        //获取当前Activity所在的窗体
        Window dialogWindow = modify_dialogs.getWindow();

        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        //        lp.y = 20;//设置Dialog距离底部的距离

        //// 以下这两句是为了保证按钮可以水平满屏
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
        // 设置显示位置
        modify_dialogs.onWindowAttributesChanged(lp);
        //       将属性设置给窗体
//        modify_dialogs.setCanceledOnTouchOutside(false);
        modify_dialogs.show();//显示对话框

        initData(beans);
        mImgClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modify_dialogs.dismiss();
            }
        });

        mTvProvince.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                province = "";
                city = "";
                mTvCity.setVisibility(View.GONE);
                mTvProvince.setVisibility(View.GONE);
                mLlSelect.setVisibility(View.VISIBLE);

                mRvProvince.setVisibility(View.VISIBLE);
                mRvCity.setVisibility(View.GONE);
                mRvArea.setVisibility(View.GONE);
                cityList.clear();
            }
        });

        mTvCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                city = "";
                mTvCity.setVisibility(View.GONE);
                areaList.clear();
                initCity();
                mRvProvince.setVisibility(View.GONE);
                mRvCity.setVisibility(View.VISIBLE);
                mRvArea.setVisibility(View.GONE);
            }
        });

    }

    private void initData(ArrayList<CityInfoBean> beans) {

        for (int i = 0; i < beans.size(); i++) {
            provinceList.add(beans.get(i).getAreaName());
        }

        initProvince();
    }

    private void initProvince() {
        mRvProvince.setVisibility(View.VISIBLE);
        mRvCity.setVisibility(View.GONE);
        mRvArea.setVisibility(View.GONE);
        mProvinceAdapter = new ProvinceAdapter(provinceList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        mRvProvince.setLayoutManager(linearLayoutManager);
        mRvProvince.setAdapter(mProvinceAdapter);
        mProvinceAdapter.setOnItemListener(new ProvinceAdapter.onItemClick() {
            @Override
            public void onClick(int position, String name) {

                s_province = beans.get(position).getAreaCode();
                s_province_name = beans.get(position).getAreaName();
                mProvinceAdapter.setSelection(position);
                mProvinceAdapter.notifyDataSetChanged();
                if (TextUtils.isEmpty(province)) {
                    province = name;
                    mTvProvince.setVisibility(View.VISIBLE);
                    mTvProvince.setText(name);
                    initCity();
                }
                mCityInfoBean = beans.get(position);
                getArea(beans.get(position).getAreaId() + "", 2);

            }
        });
        mProvinceAdapter.notifyDataSetChanged();
    }


    private void initCity() {

        mRvProvince.setVisibility(View.GONE);
        mRvCity.setVisibility(View.VISIBLE);
        mRvArea.setVisibility(View.GONE);
        mCityAdapter = new CityAdapter(cityList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        mRvCity.setLayoutManager(linearLayoutManager);
        mRvCity.setAdapter(mCityAdapter);
        mCityAdapter.setOnItemListener(new CityAdapter.onItemClick() {
            @Override
            public void onClick(int position, String name) {

                s_city = c_beans.get(position).getAreaCode();
                s_city_name = c_beans.get(position).getAreaName();

                if (TextUtils.isEmpty(city)) {
                    city = name;
                    mTvCity.setVisibility(View.VISIBLE);
                    mTvCity.setText(city);
                }

                getArea(c_beans.get(position).getAreaId() + "", 3);

            }
        });
    }

    private void initArea() {

        mRvProvince.setVisibility(View.GONE);
        mRvCity.setVisibility(View.GONE);
        mRvArea.setVisibility(View.VISIBLE);
        mAreaAdapter = new AreaAdapter(areaList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        mRvArea.setLayoutManager(linearLayoutManager);
        mRvArea.setAdapter(mAreaAdapter);
        mAreaAdapter.setOnItemListener(new AreaAdapter.onItemClick() {
            @Override
            public void onClick(int position, String name) {

                s_county = a_beans.get(position).getAreaCode();
                s_county_name = a_beans.get(position).getAreaName();

                area = name;
                mTvArea.setVisibility(View.VISIBLE);
                mTvArea.setText(area);
                mLlSelect.setVisibility(View.GONE);
                modify_dialogs.dismiss();
                address.setText(s_province_name + " " + s_city_name + " " + s_county_name);

            }
        });
    }

    public void addAddress() {

        List<String> ls = new ArrayList<>();
        ls.add(s_province+"/"+s_city+"/"+s_county);
        ls.add("");
        ls.add("");
        ls.add(name.getText().toString());
        ls.add(phone.getText().toString());
        ls.add("0");
        ls.add(eAddress.getText().toString());

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "addAddress");
        params.put("data[name]", name.getText().toString());
        params.put("data[phone]", phone.getText().toString());
        params.put("data[street]", eAddress.getText().toString());
        params.put("data[allcity]", s_province+"/"+s_city+"/"+s_county);
        params.put("data[fixed]", "");
        params.put("data[email]", "");
        params.put("data[state]", "0");

        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/mall/", params, handler, 4, 404);

    }


}
